package state;


import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Tumble;
import org.apache.flink.util.Collector;

public class StateDemo {
    public static void main(String[] args) throws Exception {
        //（1,3）（1,5）（1,7）（1,4）（1,2）
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.enableCheckpointing(2000);
        DataStreamSource<String> dataStreamSource = env.socketTextStream("linux121", 7777);
        SingleOutputStreamOperator<Tuple2<Long, Long>> maped = dataStreamSource.map(new MapFunction<String, Tuple2<Long, Long>>() {
            @Override
            public Tuple2<Long, Long> map(String s) throws Exception {
                String[] split = s.split(",");
                return new Tuple2<>(Long.valueOf(split[0]), Long.valueOf(split[1]));
            }
        });

        KeyedStream<Tuple2<Long, Long>, Long> keyed = maped.keyBy(value -> value.f0);
        SingleOutputStreamOperator<Tuple2<Long, Long>> operatored = keyed.flatMap(new RichFlatMapFunction<Tuple2<Long, Long>, Tuple2<Long, Long>>() {
            ValueState<Tuple2<Long, Long>> sumState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<Tuple2<Long, Long>> des = new ValueStateDescriptor<>("", TypeInformation.of(new TypeHint<Tuple2<Long, Long>>() {
                }), Tuple2.of(0L, 0L));
                sumState = getRuntimeContext().getState(des);
                super.open(parameters);
            }

            @Override
            public void flatMap(Tuple2<Long, Long> value, Collector<Tuple2<Long, Long>> collector) throws Exception {
                Tuple2<Long, Long> state = sumState.value();
                state.f0 += 1;
                state.f1 += value.f1;
                sumState.update(state);
            }
        });
        operatored.print();

        env.execute();
    }
}
